package protocol

import (
	"Metro/config"
	"Metro/dal"
	"Metro/dal/model"
	"Metro/dal/query"
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"jialiking.com/gaogang/common/utils"
	"net/http"
	"time"
)

var ErrIncompletePacket = errors.New("incomplete packet")
var ErrInvalidPacket = errors.New("invalid packet")

func UpdateHostOnline(mac string) {
	_, _ = query.Host.Where(query.Host.Gateway.Eq(mac)).Updates(map[string]interface{}{
		"LastReportDate": time.Now(),
	})
}

func TriggerEvent(device model.Device, threshold *model.Threshold, value string) {
	take, _ := query.Event.Where(query.Event.DeviceID.Eq(device.ID), query.Event.ThresholdID.Eq(threshold.ID)).Take()
	if take != nil {
		utils.InfoLog("event already exists")
		return
	}
	eventID := dal.GetUniqueID()
	err := query.Event.Create(&model.Event{
		ID:          eventID,
		Device:      device,
		ThresholdID: threshold.ID,
	})
	if err != nil {
		utils.ErrorLog("create event error: %v", err)
		return
	}
	utils.InfoLog("create event success")

	if threshold.Warning {
		err = query.Warning.Create(&model.Warning{
			ID:          dal.GetUniqueID(),
			EventID:     &eventID,
			DeviceID:    device.ID,
			ThresholdID: threshold.ID,
		})
		if err != nil {
			utils.ErrorLog("create warning error: %v", err)
			return
		}
		go sendWarningWS()
		utils.InfoLog("create warning success")
	}
}

func ClearEvent(device model.Device, threshold *model.Threshold, value string) {
	events, _ := query.Event.Where(query.Event.DeviceID.Eq(device.ID), query.Event.ThresholdID.Eq(threshold.ID)).Find()
	for _, event := range events {
		_, _ = query.Warning.Where(query.Warning.EventID.Eq(event.ID)).Updates(map[string]interface{}{
			"EventID":      nil,
			"RecoveryDate": time.Now(),
		})
		info, err := query.Event.Where(query.Event.ID.Eq(event.ID)).Delete()
		utils.InfoLog("delete event success: %v", info)
		if err != nil {
			utils.ErrorLog("delete event error: %s", err.Error())
			return
		}
		utils.InfoLog("clear event success and recovery warning success %d", event.ID)
	}
}

func sendWarningWS() {
	data, err := json.Marshal(map[string]any{
		"type": "warning",
		"time": time.Now().Unix(),
	})
	if err != nil {
		utils.ErrorLog(err.Error())
		return
	}
	resp, err := http.Post(fmt.Sprintf("%s/ws/", config.DjangoUrl), "application/json", bytes.NewReader(data))
	if err != nil {
		utils.ErrorLog(err.Error())
		return
	}
	defer resp.Body.Close()
	utils.InfoLog("sendWarningWS Status:", resp.StatusCode)
}
